package com.zhaoyd.uaademo.core.orm;


import com.zhaoyd.uaademo.core.BaseLogger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author zhaoyd
 * @date 2018/4/21
 */
public abstract class BaseService<T> extends BaseLogger {

    protected abstract BaseMapper<T> dao();

    @Transactional(rollbackFor = Exception.class)
    public T getByPrimaryKey(Object id){
        return dao().selectByPrimaryKey(id);
    }
    @Transactional(rollbackFor = Exception.class)
    public List<T> listAll(){
        return dao().selectAll();
    }

    public List<T> list(T queryBean){
        return dao().select(queryBean);
    }

    public T getOne(T queryBean){
        return dao().selectOne(queryBean);
    }

    public int save(T entity){
        return dao().insertSelective(entity);
    }

    public int save(List<T> list){
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }else{
            return dao().insertList(list);
        }
    }

    @Transactional(timeout=30,rollbackFor = Exception.class)
    public int update(T entity, boolean selective) {
        if(selective){
            return dao().updateByPrimaryKeySelective(entity);
        }
        else{
            return dao().updateByPrimaryKey(entity);
        }
    }
    @Transactional(timeout=30,rollbackFor = Exception.class)
    public int delete(Integer id) {
        return dao().deleteByPrimaryKey(id);
    }

    @Transactional(timeout=30,rollbackFor = Exception.class)
    public int delete(T deleteBean) {
        return dao().delete(deleteBean);
    }

    @Transactional(timeout=30,rollbackFor = Exception.class)
    public int delete(List<Integer> ids) {
        int result = 0;
        for(Integer id : ids){
            result += dao().deleteByPrimaryKey(id);
        }
        return result;
    }

    public List<T> selectByExample(Example example){
        return dao().selectByExample(example);
    }
}
